/**
 * Created by Dalyn on 2017/3/17.
 * 结算中心-给企业充值
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import GetEnAccountRecordListMutation from "./mutation/GetEnAccountRecordListMutation"
import EnterpriseRechargeMutation from "./mutation/EnterpriseRechargeMutation"
import Confirm from "../../common/Confirm"
import InputBox from "../../common/InputBox"
import RechargeSet from "./RechargeSet"
import "./css/recharge.css";
import Util from "../../util/Util";

// 充值确认弹出框
import PrepaidConfirmModal from './components/PrepaidConfirmModal'

/*导出组件*/
export default class RechargeSettlement extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            listInfo: [],
            /*收入/支出(1-收入；2-支出)*/
            /*是否发送请求*/
            // isRelay:false,
            inOrOut:"1",
            /*企业id*/
            enid: "",
            /*企业名称*/
            enterpriseName: "",
            /*流水号*/
            tranNo:"",
            /*总共多少条*/
            totalResult: "",
            /*每页条数*/
            pageItem: "",
            /*指定页码*/
            pageNum: 1,
            /*指定每页显示条数*/
            pageSize: 10,
            /*后台错误提示*/
            hint:"",
            /*测试数据*/
            listInfo:[
                {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
                {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
                {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
                {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
            ],
        };
        this.style = {
            confirm: {
                width: '96px',
                height: '27px',
                backgroundColor: "#7abd54",
                fontSize: "16px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "3px",
                marginLeft: "30px"
            },
            company: {
                width: "150px",
                height: 20,
                borderColor: "#c2df88"
            },
            conPage:{
                width: '50px',
                height: '25px',
                backgroundColor: "#7abd54",
                fontSize: "12px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "3px",
                marginLeft: "10px",
                marginTop:"-4px"
            }
        };
        this.pageNum=1;

        // 绑定 方法
        this.requestHttpInfo = this.requestHttpInfo.bind(this);
    }
    /*日期格式化*/
    dateFormat(time){
        if(time){
            let zero=(n)=>{
                return n = n>=0&&n<10 ? "0"+n : n;
            };
            let y = new Date(time).getFullYear();
            let m = new Date(time).getMonth()+1;
            let d = new Date(time).getDate();
            let h = new Date(time).getHours();
            let ms = new Date(time).getMinutes();
            return zero(y)+"-"+zero(m)+"-"+zero(d)+" "+zero(h)+":"+zero(ms);
        }
    }
    myRelay(){
        if(this.refs.priseId){
            //校验企业ID和企业名称，不符合规则的直接返回空的查询结果
            let enid = this.refs.priseId.state.text;
            let enterpriseName = this.refs.priseName.state.text;
            let tranNo = this.refs._tranNo.state.text;
            let reg_id = /^[1-9]\d{0,50}$/g;
            let reg_name = /^[a-zA-Z\u4e00-\u9fa5（）]+$/;//企业名称
            let reg_tranNo= /^\w{1,50}$/g;
            if(enid && !reg_id.test(enid)){
                this.setState({
                    listInfo: [],
                    totalResult: "0",
                    pageItem: "0",
                    pageNum: "1",
                    hint:""
                });
                this.refs.page.value=this.state.pageNum;
                return;
            }else if(enterpriseName && !reg_name.test(enterpriseName)){
                this.setState({
                    listInfo: [],
                    totalResult: "0",
                    pageItem: "0",
                    pageNum: "1",
                    hint:""
                });
                return;
            }else if(tranNo && !reg_tranNo.test(tranNo)){
                this.setState({
                    listInfo: [],
                    totalResult: "0",
                    pageItem: "0",
                    pageNum: "1",
                    hint:""
                });
                return;
            }
        }
        /*请求数据*/
        this.requestHttpInfo()
    }

    // http发送数据
    requestHttpInfo(){
        Relay.Store.commitUpdate(
            new GetEnAccountRecordListMutation({
                enid:this.state.enid,
                enterpriseName: this.state.enterpriseName,
                tranNo: this.state.tranNo,
                inOrOut:this.state.inOrOut,
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.getEnAccountRecordList.data;
                    if (data.errorCode === "0") {
                        this.setState({
                            listInfo: data.enAccountRecordList,
                            totalResult: data.totalResult,
                            pageItem: data.enAccountRecordList.length,
                        });
                        this.refs.page.value=this.state.pageNum;
                    }else {
                        this.setState({
                            hint:data.value,
                        });
                    }
                }

            }
        );
    }

    componentWillMount() {
        this.myRelay();
    }

    /*搜索*/
    search() {
        /*每点击一次搜索，默认第一页显示*/
        this.setState({
            enid:this.refs.priseId.state.text,
            enterpriseName:this.refs.priseName.state.text,
            tranNo:this.refs._tranNo.state.text,
            pageNum:"1",
            pageSize: this.state.pageSize,
            hint:""
        },this.myRelay);
        this.refs.page.value = this.state.pageNum;
    }
    /*搜索框失去焦点时，设置状态值为当前内容*/
    bluron(type){
        switch (type){
            case "page":{
                let pageNum = this.refs.page.value;

                if (pageNum<1){
                    this.setState({
                        pageNum:1
                    });
                }
                if (pageNum > this.pageTotal()){
                    this.setState({
                        pageNum:this.pageTotal()
                    });
                }
                if(this.refs.page.value == ""){
                    this.setState({
                        pageNum:this.pageNum
                    });
                }
                return;
            }
        }
    }
    /*获取焦点*/
    focuson(type){
        switch (type){
            case "priseId":
                this.setState({
                    hint:""
                });
                return;
            case "priseName":
                this.setState({
                    hint:""
                });
                return;
            case "_tranNo":
                this.setState({
                    hint:""
                });
                return;
        }
    }

    /* 操作 */
    operationModal(item){
        this.refs.PrepaidConfirmModal.open(item);
    }

    /*绑定数据*/
    addList() {
        if( null == this.state.listInfo || this.state.listInfo.length == 0){
            return (
                <tr>
                    <td>暂无相关数据</td>
                </tr>
            )
        }else{
            return this.state.listInfo.map((item, index) => {
                return (
                    <tr key={index + "_"}>
                        <td>{item.enid}</td>
                        <td title={!item.enterpriseName?"--":item.enterpriseName}>{!item.enterpriseName?"--":item.enterpriseName}</td>
                        {/*<span className="recharge_recCom_nor recharge_settle_ts1">{item.orderId}</span>*/}
                        <td>{this.doubleFormat(item.amount == "0.00" ? item.applyAmount : item.amount)}</td>
                        <td title={item.tranNo}>{item.tranNo}</td>
                        <td>{this.dateFormat(item.examineTime)}</td>
                        <td>{!item.examineBy?"--":item.examineBy}</td>
                        <td onClick={()=>{this.operationModal(item)}}><a> {item.applyStatus == "2" ? "查看" : "充值"} </a> </td>
                    </tr>
                )
            })
        }
    }

    /*数字千分制*/
    doubleFormat(obj){
        if(!obj){
            return obj;
        }else{
            return parseFloat(obj).toLocaleString();
        }
    }

    /*点击充值*/
    rechargeCompany() {
        /*清空弹框数据*/
        /*this.refs._rechargeSet.refs._priseOrder.state.text="";
        this.refs._rechargeSet.state.priseOrder="";
        this.refs._rechargeSet.refs._amount.state.text="";
        this.refs._rechargeSet.state.amount="";
        this.refs._rechargeSet.refs._flowing.state.text="";
        this.refs._rechargeSet.state.flowing="";*/
        this.refs._rechargeSet.initHit();//初始化弹框数据
    }

    /**
     * 当输入页码时进行校验
     */
    pageNumChange(e){
        let numtest = /^[0-9]*$/;
        let text = e.target.value;
        if (!numtest.test(text)) {
            return;
        }
        this.setState({
            pageNum:text
        });
    }

    /*点击确定-页码*/
    page() {
        this.bluron();
        this.setState({
            pageNum:this.refs.page.value == ""?"1":this.refs.page.value,
        },this.myRelay);
        // this.refs.page.value = this.state.pageNum;
    }

    /*总页码*/
    pageTotal(){
        return Math.ceil(this.state.totalResult / this.state.pageSize)
    }

    /*上一页*/
    leftBtn() {
        let pageNum = this.state.pageNum;
        if (pageNum <= 1) {
            return;
        } else {
            pageNum--;
            this.pageNum = pageNum;
            // this.bluron();
            this.setState({
                pageNum: pageNum,
            }, this.myRelay)
        }
    }

    /*下一页*/
    rightBtn() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum >= pageTotal) {
            return;
        } else {
            pageNum++;
            this.pageNum = pageNum;
            this.setState({
                pageNum: pageNum,
            }, this.myRelay)
        }
    }

    render() {
        return (
            <div className="recharge_recCom">
                {/*<p className="recharge_recCom_nav1">结算中心 > <span className="recharge_recCom_nav2">充值记录</span></p>*/}
                <div className="recharge_recCom_box">
                    <div className="recharge_clear">
                        <div className="recharge_settle_priseId">
                            <InputBox titletext={'企业ID：'} space={15} className="recharge_border-none" style={this.style.company} defaultvalute="请输入企业ID"
                                      maxlength={22} ref={'priseId'} bluron={this.bluron.bind(this,"priseId")} focuson={this.focuson.bind(this,"priseId")}/>
                        </div>
                        <div className="recharge_settle_priseName">
                            <InputBox titletext={'企业名称：'} className="recharge_border-none" space={15} style={this.style.company} defaultvalute="请输入企业名称"
                                      maxlength={22} ref={'priseName'} bluron={this.bluron.bind(this,"priseName")} focuson={this.focuson.bind(this,"priseName")}/>
                        </div>
                        <div className="recharge_settle_priseName">
                            <InputBox titletext={'交易流水号：'} className="recharge_border-none"  space={15} style={this.style.company} defaultvalute="请输入交易流水号"
                                      maxlength={22} ref={'_tranNo'} bluron={this.bluron.bind(this,"_tranNo")} focuson={this.focuson.bind(this,"_tranNo")}/>
                        </div>
                        <div className="recharge_settle_searchBtn">
                            <Confirm style={this.style.confirm} tcontext={'搜索'} touch={this.search.bind(this)}/>
                            <span className="recharge_settle_searchHint">{this.state.hint}</span>
                        </div>
                    </div>

                    {/*充值编辑弹框*/}
                    <RechargeSet ref={"_rechargeSet"} myRelay={this.search.bind(this)} />

                    <table className="recharge_table">
                        <thead>
                            <tr>
                                {
                                    ["企业ID","企业名称","充值金额（元）","交易流水号","充值时间","操作人","操作"].map((item,index)=>
                                        <th key={`table_th${index}`}> {item} </th>
                                    )
                                }
                            </tr>
                        </thead>
                        <tbody>
                            {
                                this.addList()
                            }
                        </tbody>
                    </table>

                    {/*充值确认弹出框*/}
                    <PrepaidConfirmModal
                        newList={this.requestHttpInfo}
                        ref="PrepaidConfirmModal"
                    />

                    {/*分页*/}
                    <div className="recharge_page clear">
                        <ol className="recharge_page_ol clear">
                            <li className="recharge_page_oli1">总计<span>{this.state.totalResult}</span>条</li>
                            <li className="recharge_page_oli2">每页<span>{this.state.pageItem}</span>条</li>
                            <li className="recharge_page_oli3">
                                共<span>{this.pageTotal()}</span>页
                            </li>
                            <li>第&nbsp;&nbsp;<input type="text" className="recharge_page_olinp" value={this.state.pageNum} onChange={this.pageNumChange.bind(this)}
                                                    ref={"page"} onBlur={this.bluron.bind(this,"page")}/>&nbsp;&nbsp;页
                            </li>
                            <li><Confirm tcontext={'确定'} style={this.style.conPage} touch={this.page.bind(this)}/>
                            </li>
                            <li className="recharge_page_olbtn">
                                <i className="recharge_page_button recharge_page_left" onClick={this.leftBtn.bind(this)}></i>
                                <i className="recharge_page_button recharge_page_right" onClick={this.rightBtn.bind(this)}></i>
                            </li>
                        </ol>
                    </div>
                </div>
            </div>
        )
    }
}
